﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetStar.TheKing.Domain;
using DotNetStar.TheKing.Infrastructure;
using Microsoft.Extensions.Caching.Memory;
using SDDP;


namespace DotNetStar.TheKing.Services
{
    public class TagService : ServiceBase
    {
        IStorage<Tag, int> _tagStorage;
        public TagService(
        IStorage<Tag, int> tagStorage, 
        IMemoryCache memoryCache) 
            : base(memoryCache)
        {
            _tagStorage = tagStorage;
        }

        /// <summary>
        /// 获取所有标签，次数升序
        /// </summary>
        /// <returns></returns>
        public Task<IEnumerable<Tag>> GetTagsAsync()
        => Task.FromResult(_tagStorage.Query().OrderByDescending(m => m.Count).ToList().AsEnumerable());

        public Task<IEnumerable<Tag>> GetHostTagsAsync(int top=10)
        => Task.FromResult(_tagStorage.Query().OrderByDescending(m => m.Count).Take(top).ToList().AsEnumerable());

        /// <summary>
        /// 保存标签，存在则次数+1，否则新增
        /// </summary>
        /// <param name="tagNames"></param>
        /// <returns></returns>
        public async Task<IEnumerable<int>> SaveTagAsync(string[] tagNames)
        {
            var existsTags = _tagStorage.Query(m => tagNames.Contains(m.Name)).ToList();
            foreach (var item in existsTags)
            {
                _tagStorage.Context.AttachIfNotExist(item);
            }
            var notExistTags = tagNames.Except(existsTags.Select(m=>m.Name));
            foreach (var item in notExistTags)
            {
                if (item.IsNullOrWhiteSpace())
                {
                    continue;
                }

                var tag = new Tag
                {
                    Name = item
                };
                tag.IncreaseCount();
                _tagStorage.Add(tag);
            }

            await _tagStorage.Context.CommitAsync();

            return _tagStorage.Query(m => tagNames.Contains(m.Name)).Select(m=>m.Id).ToList();
        }
        /// <summary>
        /// 获取指定标签id数组内的标签集合
        /// </summary>
        /// <param name="tagIds"></param>
        /// <returns></returns>
        public Task<IEnumerable<Tag>> GetTagsAsync(int[] tagIds)
            => Task.FromResult(_tagStorage.Query(m => tagIds.Contains(m.Id)).ToList().AsEnumerable());
    }
}
